<template>

    <el-dialog
      title="注：换行用<br>"
      v-model="state.visible"
      width="1200px"
    >
      <div class="dialogContent">    
        <div class="affix">
          <el-affix :offset="30">
            <el-button type="warning" @click="getEndNodeClick">获取章节</el-button>
            <div class="nodeList" v-show="state.nodeVisible">
              <el-button
                v-for="item in state.nodeList"
                :key="item.name"
                :type="getButtonType(item.id)"
                text
                size="small"
                @click="linkNodeClick(item)"
                >{{ item.name }}
              </el-button>
              <el-button
                text
                size="small"
                :type="getButtonType(2)"
                @click="state.nodeVisible=false"
              >关闭知识点</el-button>
              <el-button
                text
                size="small"
                :type="getButtonType(3)"
                @click="linkAllNodeClick"
              >全关联</el-button>
            </div>
          </el-affix>
        </div> 
        <el-form :model="state.question" :rules="state.rules" ref="questionRef" label-width="100px" class="questionForm">
          <el-form-item label="内容：" prop="content">
            <div style="width:100%;">
              <TinymceNew id="contentEditor" :value="state.question.content" :modelValue="state.question.content" @update:modelValue="inputContent" ref="contentEditorRef"></TinymceNew>        
            </div>
          </el-form-item>

          <el-form-item label="答案：" prop="answer"> 
            <div style="width:100%;">
              <QuillEditor v-model:content="state.question.answer" @update:content="handleUpdateAnswerQuill" ref="answerEditorRef" /> 
            </div>
          </el-form-item>
          <el-form-item label="解析：" prop="explain">
            <div style="width:100%;">       
              <VueQuillEditor v-model:content='state.question.explain' @update:content="handleUpdateExplainQuill" ref="explainEditorRef" />   
            </div>          
          </el-form-item>

          <!-- 设置题型 -->
          <el-form-item label="题型：" prop="type">
              <el-select v-model="state.question.type" class="m-2" placeholder="题型" size="small" @change="typeSelectChange">
                <el-option
                  v-for="item in questionTypeOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
          </el-form-item>
           
          <el-form-item>
            <el-button type="success" @click="submitUpdateClick()" v-if="isUpdate()">更新到数据库</el-button>
            <el-button type="success" @click="submitEdit()" v-if="props.type=='edit'">保存</el-button>
            <el-button type="warning" @click="resetForm()">取消</el-button>
            <el-button type="success" @click="submitEditAndPublish()"  v-if="isModify()">保存并发布</el-button>
          </el-form-item>
        </el-form>
        <div class="jiaodui">
          <h1>最终效果</h1>
          <div>【题】</div>
          <div v-html="state.question.content" class="line-break"></div>           
          <div>【答案】</div>
          <div v-html="state.question.answer" class="line-break"></div>           
          <div>【解析】</div>
          <div v-html="state.question.explain" class="line-break"></div>
          <p>【知识点】<a v-for="item in state.question.node" :key="item.id">{{ item.name }};</a></p>
          <p>【题型】{{ state.question.type_cn }}</p>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">          
          <el-button type="primary" @click="state.visible = false">关 闭</el-button>          
        </div>
      </template>
    </el-dialog>
</template>
  
<script setup>
  import { reactive, ref, onMounted, watch, computed } from 'vue'
  import { localGet, deepClone } from '@/utils'
  import { ElMessage } from 'element-plus'
  import axios from '@/utils/axios'
  import TinymceNew from "@/components/TinymceNew.vue"
  import QuillEditor from '@/components/QuillEditor.vue';
  import VueQuillEditor from '@/components/VueQuillEditor/index.vue' 
  import { useStore } from 'vuex'

  const store=useStore()
  const contentEditorRef=ref(null)      // 题干富文本编辑器 ref
  const answerEditorRef=ref(null)       // 答案富文本编辑器 ref
  const explainEditorRef = ref(null)    // 解析富文本编辑器 ref
  const questionRef = ref(null)
  const state = reactive({
    visible: false,     //控制本组件的对话框显示和隐藏
    rules: { // 规则
      content: [
        {required: 'true', message: '请填写题目内容', trigger: ['change']}
      ],      
      answer: [
        { required: 'true', message: '请填写参考答案', trigger: ['change'] }
      ],
      explain: [
        { required: 'true', message: '请填写解析', trigger: ['change'] }
      ],
    },
    token: localGet('token') || '', // 存在本地的 token
    question: Object,
    father_id: Number,
    nodeList:[],
    nodeVisible:false,
  });
  const props = defineProps({
    type:String,
    father_method:Function,
    question:Object,
  })
  const buttonTypeList = ['primary', 'success', 'info', 'warning', 'danger']
  const getButtonType =(value)=>{
    return buttonTypeList[value % buttonTypeList.length]
  }
  // 批量关联所有题目的知识点
const linkAllNodeClick=() => {
  let knowledgeIdTemp = 1
  let knowledgeNameTemp = ''
  if(state.selectIndex >= 0){
      knowledgeIdTemp = state.returnQuestionList[state.selectIndex].node[0]
      knowledgeNameTemp = state.returnQuestionList[state.selectIndex].node_cn[0]
  } else if(knowledgeIdTemp = state.returnQuestionList[0].node.length>0){
    knowledgeIdTemp = state.returnQuestionList[0].node[0]
    knowledgeNameTemp = state.returnQuestionList[0].node_cn[0]
  }else {
    ElMessage.error("请先关联第一题")
    return false;
  }
  let flag = false  
  for(let i=0; i<state.returnQuestionList.length; i++){    
    if (!state.returnQuestionList[i].node.includes(knowledgeIdTemp)){
      state.returnQuestionList[i].node.push(knowledgeIdTemp)
      state.returnQuestionList[i].node_cn.push(knowledgeNameTemp)
      flag = true
    }
  }
  if(flag == true){
    ElMessage.success("关联成功")
    return true
  }
  return false

}
  // 把知识点关联到题目
  const linkNodeClick=(node)=>{
    console.log('点击了其他章节：',node)
    if (!state.question.node.includes(node)){
      state.question.node.push(node)
    } else{
      ElMessage.warning('不能选择重复的章节！')
    }
    
  }
  // 获取某个顶端节点下的所有末端的章节
  const getEndNodeClick=()=>{
    let params = {top_node_id: store.getters.getNodeId}
    console.log("获取所有末端的章节")
    axios.get('/NodeModelViewSet/get_all_end_node',{params}).then(res => {
      console.log("获取知识点结果：",res)
      if (res.code==200){
        ElMessage.success('恭喜，获取知识点成功')
        state.nodeList = deepClone(res.data.results)
        state.nodeVisible = true     
      }else
      if(res.code==1099){
        ElMessage.error('参数错误，获取失败')
      }
      else
      if(res.code==1098){
        ElMessage.error('没有权限')
      }
      else{
        ElMessage.error('服务器错误')
      } 
    })
    .catch((error)=>{
      console.log("error:", error)
    })   
  }
  // 初始化题目
  const initQuestion=computed(()=>{
    return deepClone(props.question)
  })
  watch(initQuestion,(newVal)=>{
    console.log("监视着props.question",newVal)
  })
  // 更新从子组件vueQuillEditor发过来的更新解析
  const handleUpdateExplainQuill = (val) => {
    console.log('子组件发来解析：',val)
    state.question.explain = val
  }
  // 更新从子组件vueQuillEditor发过来的内容更新答案
  const handleUpdateAnswerQuill = (val) => {
    console.log('子组件发来答案：',val)
    state.question.answer = val
  }
  onMounted(() => {    
    
  })
  const questionTypeOption = [
    {
      value : 1,
      label : '选择题',
    },
    {
      value : 2,
      label : '填空题',
    },
  ]  

  // 题目内容富文本框tinyeditor输入
  const inputContent=(val)=> {
    state.question.content=val
    console.log("富文本输入内容",state.question.content)
  }
  // 题目内容富文本框tinyeditor输入
   const inputAnswer=(val)=> {
    state.question.answer=val
    console.log("富文本输入答案：",state.question.answer)
  }
  // tinyeditor富文本框输入解析内容
  const inputExplain=(val)=> {
    state.question.explain=val   
  }

  const typeSelectChange=(value)=>{
    // console.log("选择题型改变了", value)
    state.question.type=value
    state.question.type_cn=questionTypeOption[value-1].label
  }
  // 保存修改,并把修改后的题目返还给父组件，类型为edit
  const submitEdit=()=>{
      questionRef.value.validate((vaild, obj) => {
        if (vaild) {
          console.log("表单验证成功，我要发消息给父组件：")
          props.father_method(state.father_id, state.question)
          state.visible = false
        }else{
          ElMessage("表单没有完成！")
          console.log("表单没有通过！",obj)       
          for (let key in obj) {
            console.log("具体原因：", obj[key][0].message)
            return false;
          }
        }
      })
    }
 
  //保存修改，并发布题目(该方法未启用),被以下submitUpdateClick替代
  const submitEditAndPublish =()=>{
    if(props.type === "modifySelectedQuestion"){
      questionRef.value.validate((vaild, obj) => {
        if (vaild) {
          console.log("表单验证成功，我要发消息给父组件：")
          //执行父组件的方法，将当前题目的修改状态保存到父组件中
          props.father_method(state.father_id, state.question)
          // 持久化到数据库中,并把<br>符号转换回\n，发给后端         
          let params = {           
            answer: state.question.answer,
            explain: state.question.explain,
            content: state.question.content,
            pictures: state.question.pictures,
            reference: state.question.reference,
            type: state.question.type,
            difficulty_level: state.question.difficulty_level,
            knowledgepoint: state.question.knowledgepoint,
            open_level: 'private',
            pictures_answer: state.pictures_answer,
            pictures_explain: state.pictures_explain
          }     
          axios.post(`/questions/`,params).then(res =>{
            if (res.code == 200){
              ElMessage("恭喜你，题目发布成功，在我的创作栏目查看！")
            }else{
              ElMessage("很遗憾，题目发布失败！")
              console.log("题目发布失败：", data.message)
            }
          }) 
          state.visible = false
        }else{
          ElMessage("表单没有完成！")
          console.log("表单没有通过！",obj)       
          for (let key in obj) {
            console.log("具体原因：", obj[key][0].message)
            return false;
          }
        }
      })
    }
  }
  // 显示本对话框
  const open = (father_id, question) => {
    state.visible = true
    console.log("父组件传过来了：",father_id,deepClone(question))
    state.question = question
    state.father_id = father_id 
  };
  // 关闭弹窗
  const close = () => {
    state.visible = false
  };
 
  // 取消按钮
  const resetForm=()=>{
    state.visible = false
  }
  // 是否更新操作
  const isUpdate=()=>{
    return props.type == 'update'
  }
  // 是否为修改操作
    const isModify=()=>{
    return props.type == 'modifySelectedQuestion'
  }
  // 更新题目到数据库按钮处理
  const submitUpdateClick=()=>{
    questionRef.value.validate((vaild, obj) => {
      if (vaild) {
        let params = {
          id: state.question.id,                
          content: state.question.content,
          answer: state.question.answer,
          explain: state.question.explain,
          type: state.question.type,
          node: state.question.node,
        }
        axios.put(`/QuestionPrivateModelViewSet/${state.question.id}/`, params).then((result) => {
          if(result.code==200){
            ElMessage.success( '操作成功！')
            state.visible = false
            // 执行父组件的回调函数
            if(props.father_method)props.father_method()
          }else{
            console.log("提交错误", result)
          }       
        }).catch((error)=>{
          console.log("更新题目错误：", error)
        })
      }else{                //输出表单没有通过的原因
        console.log("表单没有通过！",obj)
        for (let key in obj) {
          console.log("具体错误：",obj[key][0].message)          
        }
      }
    })
  }
  // 将需要暴露出去的数据与方法都可以暴露出去
  defineExpose({ open, close })
</script>

<style scoped>
.affix{
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: right;
    text-align: right;
    width: 350px;
}
  .jiaodui{
    width:450px;
    border-width: 1px;
    border-color: black;
    border-style: solid;
  }

  .dialogContent{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: flex-start;
  }
  .questionForm{
    width: 700px;
    border-width: 1px;
    border-color: black;
    border-style: solid;    
  }
  .dialog-footer{
    display: flex;
    justify-content: center;
  } 
  .line-break{
    white-space: pre-wrap;
  }
  .inlineImage{
    display: inline;
    width:  150px;
    height: 100px;
  }
 
</style>